using System;
using UnityEngine;
using UnityEngine.Pool;
[DefaultExecutionOrder(-100)]
public class PoolTool : MonoBehaviour
{
    public GameObject objPrefab;

    private ObjectPool<GameObject> pool;

    private void Awake()
    {
        //初始化对象池
        pool = new ObjectPool<GameObject>(
            createFunc:() =>Instantiate(objPrefab,transform),
            actionOnGet: (obj) => obj.SetActive(true),
            actionOnRelease:(obj) => obj.SetActive(false),
            actionOnDestroy:(obj) => Destroy(obj),
            collectionCheck:false,
            defaultCapacity:10,
            maxSize:100
        );
        
        PreFillPool(6);
    }

    //预先填充对象池
    private void PreFillPool(int count)
    {
        var preFillArray = new GameObject[count];
        //获得对象
        for (int i = 0; i < count; i++)
        {
            preFillArray[i] = pool.Get();
        }
        //释放对象
        foreach (var item in preFillArray)
        {
            pool.Release(item);
        }
    }

    //从对象池中获取对象
    public GameObject GetObjectFromPool()
    {
        return pool.Get();
    }
    //将对象返回对象池
    public void ReturnObjectToPool(GameObject obj)
    {
        pool.Release(obj);
    }
}
